<?php

namespace app\admin\controller;

use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemQueue;
use think\admin\service\AdminService;
use think\admin\service\ProcessService;
use think\admin\service\QueueService;
use think\exception\HttpResponseException;
use think\facade\Log;

/**
 * 系统任务管理
 * @class Queue
 * @package app\admin\controller
 */
class Queue extends Controller
{
    /**
     * 系统任务管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        SystemQueue::mQuery()->layTable(function () {
            $this->title = '系统任务管理';
            $this->iswin = ProcessService::iswin();
            if ($this->super = AdminService::isSuper()) {
                $this->command = ProcessService::think('xadmin:queue start');
                if (!$this->iswin && !empty($_SERVER['USER'])) {
                    $this->command = "sudo -u {$_SERVER['USER']} {$this->command}";
                }
            }
        }, static function (QueryHelper $query) {
            $query->equal('status')->like('code|title#title,command');
            $query->timeBetween('enter_time,exec_time')->dateBetween('create_at');
        });
    }

    /**
     * 分页数据回调处理
     * @param array $data
     * @param array $result
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _index_page_filter(array $data, array &$result)
    {
        $result['extra'] = ['dos' => 0, 'pre' => 0, 'oks' => 0, 'ers' => 0];
        SystemQueue::mk()->field('status,count(1) count')->group('status')->select()->map(static function ($item) use (&$result) {
            if (intval($item['status']) === 1) $result['extra']['pre'] = $item['count'];
            if (intval($item['status']) === 2) $result['extra']['dos'] = $item['count'];
            if (intval($item['status']) === 3) $result['extra']['oks'] = $item['count'];
            if (intval($item['status']) === 4) $result['extra']['ers'] = $item['count'];
        });
    }

    /**
     * 重启系统任务
     * @auth true
     */
    public function redo()
    {
        try {
            $data = $this->_vali(['code.require' => '任务编号不能为空！']);
            $queue = QueueService::instance()->initialize($data['code'])->reset();
            $queue->progress(1, '>>> 任务重置成功 <<<', 0.00);
            $this->success('任务重置成功！', $queue->code);
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        }
    }

    /**
     * 添加任务
     * @auth true
     */
    public function add()
    {
      if ($this->request->isPost()) {
        $formData = $this->request->post();
        $formData['exec_data'] = explode(',', $formData['downloadId']);
        $code = sysqueue($formData['title'], $formData['command'], $later = 0, $data = $formData['exec_data'], $rscript = 0, $loops = $formData['cronTime']);
        SystemQueue::mQuery()->db()->where('code', $code)->update(['status' => $formData['status']]);
        return $this->success('添加成功！', '');
      } 
      return $this->fetch('../view/queue/add');
    }

    /**
     * 编辑任务
     * @auth true
     */
    public function edit()
    {
      SystemQueue::mForm('edit');
    }

    /**
     * 添加任务或者编辑任务前数据更正，因为前端插件无法直接提交数组
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_filter(&$data)
    {
      if ($this->request->isPost()) {
        $data['exec_data'] = json_encode(explode(',', $data['downloadId']));
      }
    }

    /**
     * 删除系统任务
     * @auth true
     */
    public function remove()
    {
        $id = $this->request->param('id');
        if(!$id){
            $this->error("失败，参数缺失");
        }
        
        $queues = SystemQueue::mQuery()->db()->where('id', 'in', $id)->select();
        foreach($queues as $queue){
            // 正在运行的任务
            if($queue['status'] != 2 || empty($queue['exec_pid'])){
                continue;
            }
            // 执行之后运行php think xadmin:queue query观察执行中的队列正常
            // 若kill进程后，数据库删除失败的话会一直显示状态:执行中（未获取到执行结果），此为正常现象，毕竟执行该任务的进程都没了，不过数据库删除99.99%不会失败的
            ProcessService::close(intval($queue['exec_pid']));
            log::notice("删除运行中的任务," . $queue['code'] . ',pid:' . $queue['exec_pid']);
        }

        SystemQueue::mDelete();
    }
}